package com.example.treasure_back.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.config.AliOSSConfig;
import com.example.treasure_back.entity.AIResultEntity;
import com.example.treasure_back.utils.AliOSSUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
public class PictureService {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private AliOSSConfig aliOSSConfig;
    @Autowired
    private TrashDataService trashDataService;

    public AIResultEntity uploadImage(InputStream inputStream, String suffix, String email){
        String fileName = RandomStringUtils.randomAlphanumeric(32).toUpperCase();
        String trainPath = aliOSSConfig.TRAIN_PATH + fileName + suffix;
        boolean status = aliOSSUtils.uploadAvatar(inputStream, trainPath);
        if (status){
            return AITest(trainPath, email);
        }
        return null;
    }

    public AIResultEntity AITest(String path, String email){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://47.103.110.118:8080/api/predict";
        HttpPost httpPost = new HttpPost(url);
        AIResultEntity resultEntity = new AIResultEntity();
        // 设置请求头
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        // 设置请求参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("image_url",aliOSSConfig.PATH+path);
        httpPost.setEntity(new StringEntity(jsonObject.toString(),"UTF-8"));
        try {
            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 响应转化
            HttpEntity entity = response.getEntity();
            JSONObject result = JSON.parseObject(EntityUtils.toString(entity));
            resultEntity.setImage(aliOSSConfig.PATH+path);
            resultEntity.setCategory(result.getString("result"));
            resultEntity.setAccuracy(Double.parseDouble(result.getString("number")));
            // 将识别数据提交到数据库
            trashDataService.addTrashData(aliOSSConfig.PATH+path,email,result.getString("number"),result.getString("result"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return resultEntity;
    }
}
